package com.sjz.yuyin;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

import org.vosk.LibVosk;
import org.vosk.LogLevel;
import org.vosk.Model;
import org.vosk.Recognizer;


/***
 * 语音转换成文字  文件的编码需要是utf-8  如果是GBk的话，解析的内容会是乱码 
 * @author Administrator
 *
 */
public class DecoderDemo {
	public static void main(String[] argv) throws IOException, UnsupportedAudioFileException {
        LibVosk.setLogLevel(LogLevel.DEBUG);
        //new Model("模型路径")是你下载的模型解压后的地址
        //InputStream ais = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream("音频路径"))); 这个是你要识别的音频地址，我用的音频格式是 wav 其他格式还没试。
        //没有模型可以去网址： https://alphacephei.com/vosk/models 下载
         //选择 Chinese 下载这两个模型 （建议都下载 small模型识别快一点）
        try (Model model = new Model("E:\\ziliao\\vosk\\vosk-model-small-cn-0.22");
        	//	try (Model model = new Model("D:\\model\\vosk-model-small-cn-0.22");
                    InputStream ais = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream("D:\\file\\TestFile.wav")));
                    Recognizer recognizer = new Recognizer(model, 16000)) {
 
            int bytes;
            byte[] b = new byte[4096];
            while ((bytes = ais.read(b)) >= 0) {
                recognizer.acceptWaveForm(b, bytes);
                 
            }
 
            System.out.println(recognizer.getFinalResult() + System.lineSeparator());
        }
    }
}
